package com.norma.netty.study.netty.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangchaofeng
 * @date 2020/10/5
 * @description
 */
public class NettyProtocolClientHandler extends SimpleChannelInboundHandler<NettyMessageProtocol> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NettyMessageProtocol msg) throws Exception {
        String content = new String(msg.getContent(), StandardCharsets.UTF_8);
        System.out.println("client接受到消息=" + content);
    }

    //通道建立时发送消息给服务端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            String msg = "Hello,你好#" + i;
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            NettyMessageProtocol messageProtocol = new NettyMessageProtocol();
            messageProtocol.setContent(bytes);
            messageProtocol.setLength(bytes.length);
            ctx.channel().writeAndFlush(messageProtocol);
        }

    }
}
